/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head==nullptr||head->next==nullptr) return nullptr;
        ListNode *fast=head->next->next, *slow=head->next;
        while(fast&&slow&&fast!=slow)
        {
            fast=fast->next, slow=slow->next;
            if(fast) fast=fast->next;
        }

        if(fast==nullptr) return nullptr;
        //slow和fast是快慢指针在环中相遇的节点
        slow=head;
        while(slow!=fast)
        {
            slow=slow->next; fast=fast->next;
        }
        return slow;
    }
};